package com.exsun.ex1077.ui.activity.vehiclelist

import android.os.Bundle
import android.view.View
import com.drake.brv.utils.*
import com.exsun.ex1077.R
import com.exsun.ex1077.app.Constant
import com.exsun.ex1077.databinding.ActivityVehicleListBinding
import com.exsun.ex1077.databinding.ListItemVehicleBinding
import com.exsun.ex1077.model.MenuPermission
import com.exsun.ex1077.network.entity.MapVehicle
import com.exsun.ex1077.ui.activity.device.DeviceAddActivity
import com.exsun.ex1077.ui.activity.vehicledetail.VehicleDetailActivity
import com.exsun.ex1077.ui.popup.ListMenuPopup
import com.lxj.xpopup.XPopup
import com.zhangping.fastjetpack.base.BaseActivity
import com.zhangping.fastjetpack.binding.visible
import com.zhangping.fastjetpack.callback.CommonCallback
import com.zhangping.fastjetpack.extend.*
import com.zhangping.fastjetpack.extend.base.parseState
import com.zhangping.fastjetpack.extend.view.afterTextChange
import com.zhangping.fastjetpack.model.Item
import com.zhangping.fastjetpack.model.Tree
import kotlinx.android.synthetic.main.activity_bounds_list.*
import kotlinx.android.synthetic.main.activity_main.view.*
import kotlinx.android.synthetic.main.activity_vehicle_list.*
import kotlinx.android.synthetic.main.activity_vehicle_list.listView
import kotlinx.android.synthetic.main.activity_vehicle_list.refreshLayout
import kotlinx.android.synthetic.main.activity_vehicle_list.searchEdit
import kotlinx.android.synthetic.main.activity_vehicle_list.searchView

/**
 * 描述：设备管理
 * 作者：ZhangPing
 * 创建时间：2022/8/9 16:24
 */
class VehicleListActivity: BaseActivity<VehicleListViewModel, ActivityVehicleListBinding>() {

    override fun title() = "设备管理"
    override fun barBgColor() = R.color.transparent
    override fun backIcon() = R.drawable.back
    override fun backColor() = R.color.color_222222
    override fun titleColor() = R.color.color_222222

    companion object{
        const val STATUS_ALL = 0
        const val STATUS_ONLINE = 1
        const val STATUS_OFFLINE = 2
        const val STATUS_NOT_ONLINE = 3
    }

    private lateinit var listMenuPopup: ListMenuPopup
    private lateinit var menuPermission: MenuPermission

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.vm = mViewModel
        menuPermission = intent.getSerializableExtra("menuPermission") as MenuPermission
        mViewModel.status.set(intent.getIntExtra("queryStatus", STATUS_ALL))
        super.initView(savedInstanceState)
        add.visible(menuPermission.add)
        listView.linear().divider {
            setDivider(1, true)
            setColor(R.color.divider.toColorRes())
        }.setup {
            addType<MapVehicle>(R.layout.list_item_vehicle)
            onBind {
                val binding = getBinding<ListItemVehicleBinding>()
                binding.edit.visible(menuPermission.edit)
                binding.delete.visible(menuPermission.remove)
            }
            onClick(R.id.rootView, R.id.video, R.id.rename, R.id.edit, R.id.delete){
                val model = getModel<MapVehicle>()
                when(it){
                    R.id.rootView -> {
                        toActivity<VehicleDetailActivity>(Bundle().apply {
                            putSerializable("model", model)
                        })
                    }
                    R.id.video -> {
                        if (!model.isHasChannel() || !model.isOnlineA()) return@onClick
                        toActivity<VehicleDetailActivity>(Bundle().apply {
                            putSerializable("model", model)
                            putBoolean("videoFirst", true)
                        })
                    }
                    R.id.rename -> {
                        showInput("设备重命名", model.vehicleNo, "请输入"){ popupView, content ->

                        }
                    }
                    R.id.edit -> {
                        toActivityForResult<DeviceAddActivity>(Bundle().apply {
                            putInt("pageType", Constant.DEVICE_MANAGE_UPDATE)
                            putString("equipmentId", model.equipmentId)
                        }){
                            if (it.resultCode != RESULT_OK) return@toActivityForResult
                        }
                        postDelayed(500){
                            listView.closeMenus()
                        }
                    }
                    R.id.delete -> {
                        showConfirm("确定删除”${model.vehicleNo}“？", "", {
                            listView.closeMenus()
                        }){
                            mViewModel.deviceDelete(model.equipmentId).observe(this@VehicleListActivity){
                                mutable.removeAt(modelPosition)
                                notifyItemRemoved(modelPosition)
                                when(model.isOnline){
                                    0 -> {
                                        //离线
                                        statusOnlineText.text = "离线（${--mViewModel.onlineCount}）"
                                    }
                                    1 -> {
                                        //在线
                                        statusOfflineText.text = "离线（${--mViewModel.offlineCount}）"
                                    }
                                    2 -> {
                                        //未定位
                                        statusNotLocationText.text = "未定位（${--mViewModel.notLocationCount}）"
                                    }
                                }
                                statusAllText.text = "全部（${--mViewModel.totalCount}）"
                            }
                        }
                    }
                }
            }
        }
        listMenuPopup = XPopup.Builder(this)
            .atView(searchView)
            .isLightStatusBar(true)
            .isViewMode(true)
            .asCustom(ListMenuPopup(this)) as ListMenuPopup
        listMenuPopup.setOnConfirmListener(object : CommonCallback{
            override fun onCall() {
                mViewModel.apply {
                    companyIds = listMenuPopup.getDeptIdList()
                    startTime = listMenuPopup.getStartDate()?.toDateStr() ?: ""
                    endTime = listMenuPopup.getEndDate()?.toDateStr() ?: ""
                    objectTypes = listMenuPopup.getManageTypeList()
                }
                refreshLayout.autoRefresh()
            }
        })
        listMenu.setOnClickListener {
            listMenuPopup.show()
        }
        refreshLayout.emptyLayout = R.layout.layout_vehicle_list_empty
        refreshLayout.onRefresh {
            mViewModel.loadData(1)
        }.autoRefresh()

        refreshLayout.onLoadMore {
            mViewModel.loadData(index)
        }

        searchEdit.afterTextChange {
            mViewModel.searchWord = it
            refreshLayout.queueRefresh(false)
        }

        statusAll.setOnClickListener {
            if (mViewModel.status.get() == STATUS_ALL || refreshLayout.isRefreshing) return@setOnClickListener
            mViewModel.status.set(STATUS_ALL)
            refreshLayout.autoRefresh()
        }
        statusOnline.setOnClickListener {
            if (mViewModel.status.get() == STATUS_ONLINE || refreshLayout.isRefreshing) return@setOnClickListener
            mViewModel.status.set(STATUS_ONLINE)
            refreshLayout.autoRefresh()
        }
        statusOffline.setOnClickListener {
            if (mViewModel.status.get() == STATUS_OFFLINE || refreshLayout.isRefreshing) return@setOnClickListener
            mViewModel.status.set(STATUS_OFFLINE)
            refreshLayout.autoRefresh()
        }
        statusNotOnline.setOnClickListener {
            if (mViewModel.status.get() == STATUS_NOT_ONLINE || refreshLayout.isRefreshing) return@setOnClickListener
            mViewModel.status.set(STATUS_NOT_ONLINE)
            refreshLayout.autoRefresh()
        }
        mViewModel.apply {
            loadDeptTree()
            loadManageTypeList()
        }
    }

    override fun onActionClick(view: View) {
        toActivityForResult<DeviceAddActivity>(Bundle().apply {
            putInt("pageType", Constant.DEVICE_MANAGE_ADD)
        }){
            if (it.resultCode != RESULT_OK) return@toActivityForResult
            val needRefresh = it.data!!.getBooleanExtra("needRefresh", false)
            if (needRefresh){
                refreshLayout.refresh()
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.apply {
            listResult.observe(this@VehicleListActivity){
                parseState(it, {
                    val list = it.page.rows ?: emptyList()
                    statusAllText.text = "全部(${it.totalCount})"
                    statusOnlineText.text = "在线(${it.onlineCount})"
                    statusOfflineText.text = "离线(${it.offlineCount})"
                    statusNotLocationText.text = "未定位(${it.notLocateCount})"
                    totalCount = it.totalCount
                    onlineCount = it.onlineCount
                    offlineCount = it.offlineCount
                    notLocationCount = it.notLocateCount
                    refreshLayout.queueAddData(list){ list.size >= mViewModel.pageSize }
                }, {
                   refreshLayout.queueRefreshException()
                })
            }
            deptTreeResult.observe(this@VehicleListActivity){
                parseState(it, {
                    Tree.updateTreeLevel(it)
                    postDelayed(100){
                        listMenuPopup.setCompanyTreeData(it)
                    }
                })
            }
            objectTypeResult.observe(this@VehicleListActivity){
                parseState(it, {
                    listMenuPopup.setManageTypeData(it.map { Item(it.key, it.value) })
                })
            }
        }
    }
}